import axios from 'axios'

export const request = axios.create({
  baseURL: 'https://conduit.productionready.io',
  // baseURL: 'http://realworld.api.fed.lagounews.com',
})

export default ({ store, redirect }) => {
  request.interceptors.request.use(
    config => {
      const { user } = store.state
      if (user && user.token)
        config.headers.Authorization = `Token ${user.token}`
      return config
    },
    err => Promise.reject(err)
  )

  request.interceptors.response.use(
    response => {
      return response.data
    },
    error => {
      /* 401 for Unauthorized requests,
       *    when a request requires authentication but it isn't provided
       * 403 for Forbidden requests,
       *    when a request may be valid but the user doesn't have
       *    permissions to perform the action
       * 404 for Not found requests,
       *    when a resource can't be found to fulfill the request
       *  */
      let status = 0
      if (error.response.data !== '') {
        status = error.response.data.errors.error.status
      } else {
        status = error.response.status
      }
      if (status === 401) {
        store.dispatch('login', null)
        redirect({ name: 'login' })
      }
      // if (status === 403) {
      //   redirect('/')
      // }
      if (status === 404) {
        redirect('/404')
      }

      return Promise.reject(error)
    }
  )
}
